//
//  WHCompanyInfoApplyVC.m
//  WHEasyBizLink
//
//  Created by shengmeng chen on 2024/11/23.
//
#define treeH  ScreenH-navHeight1-80
#define treeW  ScreenW*2/3

#import "WHCompanyInfoApplyVC.h"
#import "WHCompanyInfoApplyCell.h"
#import "SDAutoLayout.h"
#import "WHCompanyInfoApplyModel.h"
#import "WHCIAFooterView.h"
#import "WHPDFManager.h"
#import "WHScanViewController.h"
#import "WHTdsModel.h"
#import "WHCompanyInfoApplySecendCell.h"
#import "WHDataStoreTreeVC.h"
#import "WHTreeFooterView.h"
#import "WHSelectBoxView.h"
#import "WHDialog.h"
#import "WHTdsModel.h"
#import "WHTdsSelectVC.h"
#import "WHEnterpriseCompanyModel.h"
#import "NSObject+MJKeyValue.h"
#import <AVFoundation/AVFoundation.h>

@interface WHCompanyInfoApplyVC ()<UINavigationControllerDelegate>

@property (nonatomic,strong)WHCIAFooterView *footerView;
@property (nonatomic,strong)WHTreeFooterView *treeFooterView;

@property (nonatomic,strong)UIBarButtonItem *rightItem;
///树结构
@property (nonatomic,strong)WHDataStoreTreeVC *treeVC;
@property (nonatomic,strong)WHTreeManager *treeManager;
/// 当前选中的树节点
@property(nonatomic,strong) WHTreeItem *currTreeItem;

@property(nonatomic,strong)NSArray*tradeTypeModels;
@property(nonatomic,strong)NSArray*bankModels;
@property(nonatomic,strong)WHInfoModel*infoModel;
@property(nonatomic,strong)NSString*regionalTitle;
@property(nonatomic,strong)NSString*regionalCode;
@property(nonatomic,strong)WHCompanyInfoApplyModel *comCodemodel;

@end

@implementation WHCompanyInfoApplyVC
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    self.title = @"单位信息申报";
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear: animated];
    self.treeVC.tableView.hidden = YES;
    self.treeFooterView.hidden = YES;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    self.treeFooterView.hidden = NO;
    self.treeFooterView.hidden = NO;
}

#pragma mark - loadDatas
- (void)loadDatas{
    [super loadDatas];
    
    if (self.type ==WHInfoApplyTypeAdd) {
        
        [WHCompanyInfoApplyModel fetchDatasSuccessBlock:^(id  _Nonnull models) {
            self.datas =[NSMutableArray arrayWithArray:models];
        }];
    }else if (self.type ==WHInfoApplyTypeMDF||self.type ==WHInfoApplyTypeReview)
    {
        [WHCompanyInfoApplyModel fetchDatasWithModel:self.model SuccessBlock:^(id  _Nonnull models) {
            
            self.datas =[NSMutableArray arrayWithArray:models];
        }];
    }
   
    [WHRegionalModel getTDSRegionalWithPid:@"0" Block:^(id  _Nonnull responseObject) {
        
        self.treeManager = [WHRegionalModel getTreeDatasWtihArr:(NSArray*)responseObject];
        self.treeVC.manager = self.treeManager;
        [self.treeVC setDefaultSelectFirsCell];
        } FailureBlock:^(NSString * _Nonnull msg) {
            
        }];
}
-(void)setModel:(WHEnterpriseCompanyModel *)model
{
    _model = model;
}
#pragma mark - setupUI
- (void)setupUI{
    [super setupUI];
    //一个简单的super setupUI = createTableView
    self.tableView.frame =CGRectMake(0,navHeight1,ScreenW,ScreenH-navHeight1);
    
    if (self.type ==WHInfoApplyTypeReview) {
    }else
    {
        self.tableView.tableFooterView = self.footerView;
    }
    
    
    __weak __typeof(self) weakSelf = self;
    //提交
    self.footerView.clickBtnBlock = ^(UIButton * _Nonnull btn) {
        [weakSelf.view endEditing:YES];
        
        weakSelf.infoModel = [WHInfoModel changeWHCompanyInfoApplyModels:weakSelf.datas];
        
        [WHInfoModel checkItem:weakSelf.infoModel succesefulBlock:^(NSString * _Nonnull str) {
            
            NSDictionary *dict =  [WHTdsModel getSelTDSProxyList];
            NSArray *allkey = [dict allKeys];
            if (allkey.count==0) {
            WHTdsSelectVC*vc =[[WHTdsSelectVC alloc]init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
            }else{
                [[WHDialog sharedManager] showHudWithText:@"正在申报..."];
                
                WHComOPType  opertype = WHComTypeAdd;
                if (self.type ==WHInfoApplyTypeAdd) {
                   opertype =WHComTypeAdd;
                }else if (self.type ==WHInfoApplyTypeMDF)
                {
                    opertype =WHComTypeMDF;
                    weakSelf.infoModel.comid = weakSelf.model.comid;
                }
                
            [WHInfoModel sendCompanyInfo:weakSelf.infoModel withTSD:dict withopertype:opertype withBlock:^(id  _Nonnull responseObject) {
                [[WHDialog sharedManager] dismissWithView];
                DebugLog(@"注册单位成功");
                
                NSArray* models =(NSArray*)responseObject;
                NSDictionary *dic =models.firstObject;
                
                if (dic!=nil) {
                    WHEnterpriseCompanyModel *model=[WHEnterpriseCompanyModel  objectWithKeyValues:dic];
                    
                    
                    if (self.type ==WHInfoApplyTypeAdd) {
                        if (weakSelf.registerSuccessBlock) {
                            weakSelf.registerSuccessBlock(model);
                        }
                    }else if (self.type ==WHInfoApplyTypeMDF)
                    {
                        if (weakSelf.modifySuccessBlock) {
                            weakSelf.modifySuccessBlock(model);
                        }
                    }
                }
                
                sleep(1);
                
                [weakSelf.navigationController popViewControllerAnimated:YES];

                    } failureBlock:^(NSString * _Nonnull msg) {
                        DebugLog(@"注册单位失败");
                        [[WHDialog sharedManager] showHudErrorWithText:msg];
                }];
            }
            
        } andFailureBlock:^(NSString * _Nonnull error) {
            
            [[WHDialog sharedManager] showHudAlertWithText:error];
        }];
    };
    
    self.navigationItem.rightBarButtonItem =self.rightItem;
    
    [self addChildViewController:self.treeVC];
    [self.treeVC didMoveToParentViewController:self];
    //self.treeVC.view.backgroundColor =[UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.treeVC.view];

    [self.view addSubview:self.treeFooterView];
   
    self.treeFooterView.clickBtnBlock = ^(UIButton * _Nonnull btn) {
        
        for(int i=0;i<weakSelf.datas.count;i++)
        {
            WHCompanyInfoApplyModel *model =  weakSelf.datas[i];
            if ([model.titleName isEqualToString:kComRegion]) {
                model.contents =  weakSelf.regionalTitle;
                model.code     = weakSelf.regionalCode;
                [weakSelf.tableView reloadData];
                [weakSelf treeVCShow:NO];
            }
        }
       
    };
    
    [self.treeVC setOutlineSelectPageBlock:^(WHTreeItem *item,NSIndexPath *indexPath) {
        //拼名称
        NSString *title = @"";
        NSString *code  = @"";
        if(item.parentItem){
            if(item.parentItem.parentItem){
                title = [NSString stringWithFormat:@"%@%@%@",item.parentItem.parentItem.name,item.parentItem.name,item.name];
                code  = item.ID;
            }else{
                title = [NSString stringWithFormat:@"%@%@",item.parentItem.name,item.name];
                code  = item.ID;
            }
        }else{
            title = [NSString stringWithFormat:@"%@",item.name];
               code  = item.ID;
        }
        weakSelf.regionalTitle = title;
        weakSelf.regionalCode  = code;
        NSLog(@"title = %@",title);
        //[weakSelf setViewTitleBtnWithTitle:title button:weakSelf.viewTitleBtn];
        //点击同一个节点时不处理
        if(weakSelf.currTreeItem == item){
        
                return;
         }
        weakSelf.currTreeItem = item;
        
        if(item.isLeaf==NO){
            
            [WHRegionalModel getTDSRegionalWithPid:item.ID Block:^(id  _Nonnull responseObject) {
                NSArray *arr = (NSArray*)responseObject;
                if (arr.count==0) {
                    item.isLeaf = YES;
                    [weakSelf.treeVC expandItem:item];
                }else
                {
                    weakSelf.treeManager = [WHRegionalModel writeTreeChildWtihArr:(NSArray*)responseObject treeManager:weakSelf.treeManager parentID:item.ID];
                    weakSelf.treeVC.manager = weakSelf.treeManager;
                    [weakSelf.treeVC expandItem:item];
                }
              
                } FailureBlock:^(NSString * _Nonnull msg) {
                    
                }];
        }else
        {   weakSelf.treeVC.manager = weakSelf.treeManager;
            [weakSelf.treeVC expandItem:item];
        }
    
    }];
    
    // 即将隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    // 键盘的Frame值即将发生变化的时候创建的额监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}
-(void)loadMoreDatas
{
    [super loadMoreDatas];
}

-(void)rightBarButtonItemClicked
{
    WHScanViewController *scanVC = [[WHScanViewController alloc] init];

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (status) {
            case AVAuthorizationStatusNotDetermined: {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            scanVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:scanVC animated:YES];;
                        });
                        NSLog(@"用户第一次同意了访问相机权限 - - %@", [NSThread currentThread]);
                    } else {
                        NSLog(@"用户第一次拒绝了访问相机权限 - - %@", [NSThread currentThread]);
                    }
                }];
                break;
            }
            case AVAuthorizationStatusAuthorized: {
                scanVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:scanVC animated:YES];
                break;
            }
            case AVAuthorizationStatusDenied: {
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url])
                    {
                    [[UIApplication sharedApplication] openURL:url];
                    }
                }];
                
                [alertC addAction:alertA];
                alertC.modalPresentationStyle = UIModalPresentationFullScreen;
                [self presentViewController:alertC animated:YES completion:nil];
                break;
            }
            case AVAuthorizationStatusRestricted: {
                NSLog(@"因为系统原因, 无法访问相册");
                break;
            }
            default:
                break;
        }
        return;
    }
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertC addAction:alertA];
    [self presentViewController:alertC animated:YES completion:nil];
    
}

#pragma mark - <tableViewDelegate>
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    WHCompanyInfoApplyModel*model = self.datas[indexPath.row];
    if (model.isSelect) {
        
        WHCompanyInfoApplySecendCell*cell =[WHCompanyInfoApplySecendCell
                                            createReuseIdentifier:@"WHCompanyInfoApplySecendCell" WithTableView:tableView];
        cell.model  = model;
        cell.contentView.backgroundColor =RGBColor(250, 250, 250);
        
        if (self.type ==WHInfoApplyTypeReview) {
            cell.userInteractionEnabled = NO;
        }
        
        return cell;
    }else
    {
        WHCompanyInfoApplyCell *cell = [WHCompanyInfoApplyCell
                                         createReuseIdentifier:@"WHCompanyInfoApplyCellID" WithTableView:tableView];
        cell.tag    = indexPath.row;
        cell.model  = model;
        cell.contentView.backgroundColor =RGBColor(250, 250, 250);
        if (self.type ==WHInfoApplyTypeReview) {
            cell.userInteractionEnabled = NO;
        }
        cell.clickBtnBlock = ^(WHCompanyInfoApplyModel * _Nonnull model,int index) {
           
            if ([model.titleName isEqualToString:kComType]) {
                
                [WHTradeTypeModel getTDSSystemWithBlock:^(id  _Nonnull responseObject) {
                    
                    self.tradeTypeModels =(NSArray*)responseObject;
                    WHSelectBoxView *boxView=[[WHSelectBoxView alloc]init];
                    [boxView mybuttonwithArr:[WHTradeTypeModel getTitleUnitTypeInfo: self.tradeTypeModels] andTitle:@"请您选择单位类型"andMessage:@""];
                    
                    boxView.finishBlock = ^(NSIndexPath *indexPath) {
                        WHTradeTypeModel *typeModel = self.tradeTypeModels[indexPath.row];
                        for(int i=0;i<self.datas.count;i++)
                        {
                            WHCompanyInfoApplyModel *model =  self.datas[i];
                            if ([model.titleName isEqualToString:kComType]) {
                                model.contents = typeModel.name;
                                model.code     = typeModel.code;
                                [self.tableView reloadData];
                            }
                    
                        }
                        
                        BOOL isExsit = NO;
                        for(int i=0;i<self.datas.count;i++)
                        {
                            WHCompanyInfoApplyModel *model =  self.datas[i];
                            if ([model.titleName isEqualToString:kComCode]) {
                                isExsit = YES;
                            }
                    
                        }
                        if ([typeModel.code isEqualToString:kComType99]) {
                            
                            if (isExsit==NO) {
                              WHCompanyInfoApplyModel *model =[WHCompanyInfoApplyModel new];
                              model.titleName  = kComCode;
                              model.holderName = @"例如:91110108MA01A12345";
                              model.isMust     = YES;
                              [self.datas insertObject:model atIndex:2];
                                [self.tableView reloadData];
                            }
            
                        }else
                        {
                            if (isExsit==YES) {
                                [self.datas removeObjectAtIndex:2];
                                [self.tableView reloadData];
                            }
                           
                        }
                
                    };
                    
                    [self.view addSubview:boxView];
                    [boxView showAlert];
                    [boxView setDefaultSelectRow:0];
                    } FailureBlock:^(NSString * _Nonnull msg) {
                        
                    }];
                
            }else if ([model.titleName isEqualToString:kBanknm])
            {
                    self.bankModels =[WHBankModel getWHBankModels];
                    WHSelectBoxView *boxView=[[WHSelectBoxView alloc]init];
                    
                    [boxView mybuttonwithArr:[WHBankModel getWHBankTitle] andTitle:@"请您选择银行名称"andMessage:@""];
                    
                    boxView.finishBlock = ^(NSIndexPath *indexPath) {
                        WHBankModel *bankModel = self.bankModels[indexPath.row];
                        for(int i=0;i<self.datas.count;i++)
                        {
                            WHCompanyInfoApplyModel *model =  self.datas[i];
                            if ([model.titleName isEqualToString:kBanknm]) {
                                
                                model.contents = bankModel.bankName;
                                model.code     = bankModel.bankID;
                                [self.tableView reloadData];
                            }
                    
                        }
                        
                    };
                    
                    [self.view addSubview:boxView];
                    [boxView showAlert];
                    [boxView setDefaultSelectRow:0];
                   
                }
            
            else if ([model.titleName isEqualToString:kComRegion])
            {
                [self.view endEditing:YES];
                [self treeVCShow:YES];
            }
        };
        return cell;
   }
}

//点屏幕退出键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (CGFloat)tableView:(UITableView *)tableView
 heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 100;
}
-(void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.datas removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugLog(@"tableView = %ld",(long)indexPath.row);
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
   return NO;
}

#pragma mark - <searchViewDelegate>
-(void)searchTileViewTextFieldDidChange:(NSString *)textFieldString
{
    
}
-(void)searchTileViewSearchButtonClickSearchString:(NSString *)searchString
{
}

-(void)treeVCShow:(BOOL)isShow
{
    if (isShow) {
        //展示
        [UIView animateWithDuration:(0.5)  //动画持续时间
                                 animations:^{
                               //执行的动画
            self.treeVC.view.frame =CGRectMake(0,navHeight1,treeW,treeH);
            self.treeFooterView.frame = CGRectMake(0,ScreenH-80, treeW, 80);
                }completion:^(BOOL finished) {
        
                }];
        self.tableView.userInteractionEnabled = NO;
    }else
    {    //隐藏
        [UIView animateWithDuration:(0.5)  //动画持续时间
                                 animations:^{
                               //执行的动画
            self.treeVC.view.frame =CGRectMake(-ScreenW,navHeight1,treeW,treeH);
            self.treeFooterView.frame = CGRectMake(-ScreenW,ScreenH-80, treeW, 80);
            
                }completion:^(BOOL finished) {
        
                }];
        self.tableView.userInteractionEnabled = YES;
    }
}

/**
 *   在控制器里面添加键盘的监听，
 *
 *  @return
 */
#pragma mark - Private Methods
- (void)keyboardWillHide:(NSNotification *)notification{
  
    self.tableView.frame =CGRectMake(0,navHeight1,ScreenW,ScreenH-navHeight1);
}

/**
 *
 
 */
- (void)keyboardFrameWillChange:(NSNotification *)notification{
    
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableView.frame =CGRectMake(0,navHeight1,ScreenW,ScreenH-navHeight1-keyboardFrame.size.height);
}

-(WHCIAFooterView *)footerView
{
    if (!_footerView) {
        
        _footerView = [[WHCIAFooterView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, kMarginH*14)];
    }
    return _footerView;
}

-(WHTreeFooterView *)treeFooterView
{
    if (!_treeFooterView) {
        
        _treeFooterView = [[WHTreeFooterView alloc]initWithFrame:CGRectMake(-(ScreenW),ScreenH-80, treeW, 80)];
    }
    return _treeFooterView;
}

-(UIBarButtonItem *)rightItem
{
    if (!_rightItem)
    {
        UIButton* rightBtn= [[UIButton alloc] initWithFrame:CGRectMake(0,0,25,25)];
      [rightBtn addTarget:self action:@selector(rightBarButtonItemClicked)forControlEvents:UIControlEventTouchUpInside];
        [rightBtn setBackgroundImage:[UIImage imageNamed:@"scan"] forState:UIControlStateNormal];
        _rightItem =[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    }
    return _rightItem;
}

#pragma mark 初始化
-(WHDataStoreTreeVC *)treeVC
{
    if(!_treeVC)
    {
        _treeVC = [[WHDataStoreTreeVC alloc]init];
        _treeVC.view.frame =CGRectMake(-ScreenW,navHeight1,treeW,treeH);
        _treeVC.isSingleCheck = YES;
    }
    return _treeVC;
}
-(WHInfoModel *)infoModel
{
    if(!_infoModel)
    {
        _infoModel = [[WHInfoModel alloc]init];
    }
    return _infoModel;
}

- (void)dealloc{
    /**
     *  移除键盘通知
     */
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

@end
